#!/usr/bin/env node
const path = require("path");
const program = require("commander");
const process = require("process");
const pka = require("../package.json");
const ora = require("ora");
const fs = require("fs");
const utils = require("./utils");
const toPromise = require("./utils/toPromise");
const { execCmd, exec, cd } = require("./utils/cmd");
const zipName = "dist.tgz";
const logPath = path.resolve(__dirname, "../logs/app.log");
const { types, isLog, config, zip, parallel } = utils.getConfig();
const logger = require("./utils/logger")(isLog);


/**
 * 初始化
 */
async function init() {
  await toPromise(utils.logTag);
  program
    .version(pka.version, "-v, --version")
    .option("publish, publish", "本地打包发布工具")
    .command("publish")
    .action(async () => {
      //选择配置类型
      const devType = await toPromise(utils.getSelect, types);
      const selectConfig = config[devType];
      const spinner = ora("开始打包...");
       const buildStart = Date.now();
      try {
        spinner.start();
        logger.info(`配置: ${JSON.stringify(selectConfig)}`);
        logger.info(`执行命令:${selectConfig.script}`);
       
        // 执行打包命令
        await execCmd(selectConfig.script, {
          verbose: true,
          stdio: "inherit",
        });
        const buildend = Date.now();
        spinner.succeed();
        logger.info(
          `${selectConfig.script}已完成,耗时：${
            (buildend - buildStart) / 1000
          }s`
        );
      } catch (err) {
        logger.error(err);
        spinner.fail();
        utils.notify(err,'error')
      }
      // 打zip包
      if (zip) {
        try {
          logger.info("开始压缩");
          // cd dist && tar -zcvf dist.tgz *
          await cd(selectConfig.localDir);
          logger.info(`当前工作路径：${process.cwd()}`);
          // 也可以使用archiver
          const toZip = `tar -zcvf ${zipName} *`;
          await exec(toZip);
          logger.info("压缩完成");
        } catch (err) {
          logger.error(err);
          utils.notify(err,'error')
        }
      }
      const upSpinner = ora("上传文件...");
      try {
        // 上传远程服务器
        await utils.loopUpdate(selectConfig, {
          isLog,
          zip,
          upSpinner,
          parallel,
        });
        if (zip) {
          logger.info("删除zip");
          // 删除本地
          await fs.unlinkSync("dist.tgz");
        }
        utils.notify(`任务完成，共耗时${ (Date.now() - buildStart) / 1000}s`)
      } catch (err) {
        logger.error(err);
        upSpinner.fail();
        utils.notify(err,'error')
      }
      logger.warn(`日志已记录：${logPath}`);
      // process.exit(0);
    });
  program.parse(process.argv);
}
init();
